﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.Security;
using FineUI;
using mydddd.Web.code;
using Maticsoft.DBUtility;



public class BasePage : System.Web.UI.Page
{

    #region 初始化语言和皮肤
    protected override void OnInit(EventArgs e)
    {
        var pm = PageManager.Instance;

        // 如果不是FineUI的AJAX回发（两种情况：1.页面第一个加载 2.页面非AJAX回发）
        if (pm != null && !pm.IsFineUIAjaxPostBack)
        {
            HttpCookie themeCookie = Request.Cookies["Theme_v4"];
            if (themeCookie != null)
            {
                try
                {
                    string themeValue = themeCookie.Value;
                    pm.Theme = (Theme)Enum.Parse(typeof(Theme), themeValue, true);
                }
                catch (Exception)
                {
                    pm.Theme = FineUI.Theme.Neptune;
                }
            }

            pm.Language = Language.ZH_CN;
            //HttpCookie langCookie = Request.Cookies["Language_v4"];
            //if (langCookie != null)
            //{
            //    try
            //    {
            //        string langValue = langCookie.Value;
            //        pm.Language = (Language)Enum.Parse(typeof(Language), langValue, true);
            //    }
            //    catch (Exception)
            //    {
            //        pm.Language = Language.ZH_CN;
            //    }
            //}
        }


        base.OnInit(e);
    }
    #endregion

    #region 页面权限相关

    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["Admin"] == null)//网站管理员登录
        {
            //Response.Redirect("~/timeout.aspx", true);
            //PageContext.Refresh("~/timeout.aspx");
            //PageContext.RegisterStartupScript("alert('登录超时,请重新登录');top.location.href='/login.aspx'");

            FormsAuthentication.SignOut();
            Response.Redirect(FormsAuthentication.DefaultUrl);

            //Response.Write("<script>alert('登录超时,请刷新页面重新登录');top.location.href='/login.aspx'</script>");
            //Response.End();



        }
    }

    /// <summary>
    /// 页面权限验证
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            if (Session["Admin"] == null)//网站管理员登录
            {
                Response.Write("您无权限浏览");
                Response.End();
            }
            else
            {
                string url = HttpContext.Current.Request.Url.AbsolutePath.ToLower().Replace("/admin/", "");

                //默认页和修改密码页排除验证
                switch (url)
                {
                    case "default.aspx": //默认页
                    //break;
                    case "edit.aspx"://修改密码页
                        break;
                    default:
                        DataRow dr = Session["Admin"] as DataRow;
                        if (!mydddd.BLL.SysModule.IsRole(int.Parse(dr["sysrolepopedom_rname"].ToString()), url))
                        {
                            Response.Write("您无权限浏览");
                            Response.End();
                        }
                        break;
                }
            }
            
        }
    }

    #endregion

    #region  数据操作，分页相关
    /// <summary>
    /// 绑定FineUI.Grid分页方法
    /// </summary>
    /// <param name="grid">FineUI.Grid</param>
    /// <param name="tableName">表名</param>
    /// <param name="strSql">where条件(加and)</param>
    /// <param name="orderbyColumn">排序条件</param>
    public void BindFineUI(FineUI.Grid grid, string tableName, string strSql, string orderbyColumn)
    {
        BindFineUI(" * ", grid, tableName, strSql, orderbyColumn);
    }

    /// <summary>
    /// 绑定FineUI.Grid分页方法
    /// </summary>
    /// <param name="columns">显示列名</param>
    ///  <param name="grid">FineUI.Grid</param>
    /// <param name="tableName">表名</param>
    /// <param name="whereSql">where条件(加and)</param>
    /// <param name="orderbyColumn">排序条件</param>
    public void BindFineUI(string columns, FineUI.Grid grid, string tableName, string whereSql, string orderbyColumn)
    {
        FineuiHelper.Grid.BindFineUI(columns,  grid,  tableName,  whereSql,  orderbyColumn);
    }

    /// <summary>
    /// 绑定FineUI.Grid分页方法
    /// </summary>
    /// <param name="columns">显示列名</param>
    ///  <param name="grid">FineUI.Grid</param>
    /// <param name="tableName">表名</param>
    /// <param name="whereSql">where条件(加and)</param>
    /// <param name="orderbyColumn">排序条件</param>
    public void BindFineUI2(string columns, FineUI.Grid grid, string tableName, string whereSql, string orderbyColumn)
    {
        int pageindex = grid.PageIndex;

        if (orderbyColumn.Length == 0)
        {
            orderbyColumn = string.Format(" {0} {1} ", grid.SortField, grid.SortDirection);
        }

        string sql = string.Format(@"select  {0},row_number() over(order by {1}) rid into #tt from {2} 
            where isdel=0 {3} Order By {1}  select * from  #tt where rid> {4} and rid<={5} drop table  #tt", 
                            columns, orderbyColumn, tableName, whereSql, grid.PageSize * pageindex, grid.PageSize * (pageindex + 1));
        grid.RecordCount = Getdatatablecount(string.Format("select count(1) from {0}  where isdel=0 {1}", tableName, whereSql));
        DataTable dt = GetPagedDataTable(sql);
        DataView view1 = dt.DefaultView;
        view1.Sort = orderbyColumn;
        grid.DataSource = null;
        grid.DataSource = view1;
        grid.DataBind();
    }


    /// <summary>
    /// 绑定FineUI.Grid分页方法 获取删除的页面
    /// </summary>
    /// <param name="columns">显示列名</param>
    ///  <param name="grid">FineUI.Grid</param>
    /// <param name="tableName">表名</param>
    /// <param name="strSql">where条件(加and)</param>
    /// <param name="orderbyColumn">排序条件</param>
    public void BindFineUI_del(string columns, FineUI.Grid grid, string tableName, string strSql, string orderbyColumn)
    {

        if (orderbyColumn.Length == 0)
        {
            orderbyColumn = string.Format(" {0} {1} ", grid.SortField, grid.SortDirection);
        }

        string sql = string.Format(@"select  {0},row_number() over(order by {1}) rid into #tt from {2} 
                                where isdel=1 {3} Order By {1}  select * from  #tt where rid> {4} and rid<={5} drop table  #tt", 
                                columns, orderbyColumn, tableName, strSql, grid.PageSize * grid.PageIndex, grid.PageSize * (grid.PageIndex + 1));
        grid.RecordCount = Getdatatablecount(string.Format("select count(1) from {0}  where isdel=1 {1}", tableName, strSql));
        DataTable dt = GetPagedDataTable(sql);
        DataView view1 = dt.DefaultView;
        view1.Sort = orderbyColumn;
        grid.DataSource = null;
        grid.DataSource = view1;
        grid.DataBind();
    }

    /// <summary>
    /// 绑定FineUI.Grid分页方法
    /// </summary>
    /// <param name="columns">显示列名</param>
    ///  <param name="grid">FineUI.Grid</param>
    /// <param name="tableName">表名</param>
    /// <param name="whereSql">where条件(加and)</param>
    /// <param name="dic">条件参数和赋值</param>
    /// <param name="orderbyColumn">排序条件</param>
    public void BindFineUI(string columns, FineUI.Grid grid, string tableName, string whereSql, Dictionary<string, object> dic, string orderbyColumn)
    {
        FineuiHelper.Grid.BindFineUI(columns,  grid,  tableName,  whereSql,  dic,  orderbyColumn);
    }

    /// <summary>
    /// 查询数据库记录条数
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    private int Getdatatablecount(string sql)
    {
        string cnt = DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString();
        return Convert.ToInt32(cnt);
    }

    /// <summary>
    /// 查询数据库记录条数
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    private int Getdatatablecount(string sql, SqlParameter[] par)
    {
        string cnt = DbHelperSQL.Query(sql, par).Tables[0].Rows[0][0].ToString();
        return Convert.ToInt32(cnt);
    }

    /// <summary>
    /// 数据库分页查询语句
    /// </summary>
    /// <returns></returns>
    private DataTable GetPagedDataTable(string sql)
    {
        DataSet ds = DbHelperSQL.Query(sql);
        return ds.Tables[0];
    }

    /// <summary>
    /// 数据库分页查询语句
    /// </summary>
    /// <returns></returns>
    private DataTable GetPagedDataTable(string sql, SqlParameter[] par)
    {
        DataSet ds = DbHelperSQL.Query(sql, par);
        return ds.Tables[0];
    }

    /// <summary>
    /// 动态添加数据
    /// </summary>
    /// <param name="tableName">表名</param>
    /// <param name="dic">参数和对应值集合</param>
    /// <returns>新添加数据id</returns>
    public int InsertDB(string tableName, Dictionary<string, object> dic)
    {
        DBControl control = new DBControl();
        return control.InsertDB(tableName, dic);
    }

    /// <summary>
    /// 动态更新数据
    /// </summary>
    /// <param name="tableName">表名</param>
    /// <param name="dic">参数和对应值集合</param>
    /// <param name="dicWhere">where条件参数和对应值集合</param>
    /// <returns>是否更新成功！</returns>
    public bool UpdateDB(string tableName, Dictionary<string, object> dic, Dictionary<string, object> dicWhere)
    {
        DBControl control = new DBControl();
        return control.UpdateDB(tableName, dic, dicWhere);
    }


    /// <summary>
    /// 伪删除(表有isdel字段才可以)
    /// </summary>
    /// <param name="tablename">表名</param>
    /// <param name="isdel">0显示，1删除</param>
    /// <param name="ids">多个id</param>
    /// <returns></returns>
    public int IsDelSet(string tablename, int isdel, string ids)
    {
        string sql = string.Format("update {0} set isdel={1} where id in ({2}) ", tablename, isdel, ids);
        return DbHelperSQL.ExecuteSql(sql);
    }

  


    #endregion

    #region Fineui公共方法 
    
    #region Alert 或 页面跳转

    /// <summary>
    /// 提示信息(弹层用),并指定父页面跳转
    /// </summary>
    /// <param name="message">内容</param>
    /// <param name="url"></param>
    protected void AlertInforAndRedirect(string message, string url)
    {
        FineuiHelper.Alert.AlertInforAndRedirect(message,  url );
    }

    /// <summary>
    /// 提示信息(弹层用)
    /// </summary>
    /// <param name="message">内容</param>
    /// <param name="isPostBackReference">是否回发刷新页面</param>
    protected void AlertInfor(string message, bool isPostBackReference)
    {
        FineuiHelper.Alert.AlertInfor(message, isPostBackReference);
    }

    /// <summary>
    /// 不带关闭按钮的提示框(结合window的Onclose事件使用)
    /// </summary>
    /// <param name="message">消息</param>
    protected void AlertInforNoClose(string message)
    {
        FineuiHelper.Alert.AlertInforNoClose(message,ActiveWindow.GetHidePostBackReference());
    }

    /// <summary>
    /// 不带关闭按钮的提示框
    /// </summary>
    /// <param name="message">消息</param>
    /// <param name="js">点击确定后执行的js脚本</param>
    protected void AlertInforNoClose(string message,string js)
    {
        FineuiHelper.Alert.AlertInforNoClose(message, js);
    }

    /// <summary>
    /// 提示信息（单页用 并刷新当前页）
    /// </summary>
    /// <param name="message">内容</param>
    /// <param name="isPostBackReference">是否回发刷新页面</param>
    protected void AlertInforBySingerPage(string message, bool isPostBackReference)
    {
        FineuiHelper.Alert.AlertInforBySingerPage(message, isPostBackReference);

    }

    /// <summary>
    /// 报错信息
    /// </summary>
    /// <param name="message">内容</param>
    /// <param name="isPostBackReference">是否回发刷新页面</param>
    protected void AlertError(string message, bool isPostBackReference)
    {
        FineuiHelper.Alert.AlertError(message, isPostBackReference);
    }

    /// <summary>
    /// 疑问信息
    /// </summary>
    /// <param name="message">内容</param>
    /// <param name="isPostBackReference">是否回发刷新页面</param>
    protected void AlertQuestion(string message, bool isPostBackReference)
    {
        FineuiHelper.Alert.AlertQuestion(message, isPostBackReference);
    }

    /// <summary>
    /// 警告信息
    /// </summary>
    /// <param name="message">内容</param>
    /// <param name="isPostBackReference">是否回发刷新页面</param>
    protected void AlertWarning(string message, bool isPostBackReference)
    {
        FineuiHelper.Alert.AlertWarning(message, isPostBackReference);
    }

    /// <summary>
    /// 子页面关闭并在父业面跳转
    /// </summary>
    /// <param name="url"></param>
    protected void ParentRedirect(string url)
    {
        FineuiHelper.Alert.ParentRedirect(url);
    }

     #endregion

    #region grid

    /// <summary>
    /// 获取选中行的主id，第一主键
    /// </summary>
    /// <param name="grid">FineUI.Grid</param>
    /// <returns></returns>
    public static string GetDataKeysBySelectedRow(FineUI.Grid grid)
    {
        return FineuiHelper.Grid.GetDataKeysBySelectedRow(grid, 0);
    }

    /// <summary>
    /// 获取选中行的主id
    /// </summary>
    /// <param name="grid">FineUI.Grid</param>
    /// <param name="keyNumIndex">第几个主键（从0开始）</param>
    /// <returns></returns>
    public static string GetDataKeysBySelectedRow(FineUI.Grid grid, int keyNumIndex)
    {
        return FineuiHelper.Grid.GetDataKeysBySelectedRow(grid, keyNumIndex);
    }
    #endregion
    
    #endregion

    #region Cookie操作
    /// <summary>
    /// cookies赋值
    /// </summary>
    /// <param name="strName">主键</param>
    /// <param name="strValue">键值</param>
    /// <param name="strMinutes">有效分钟数</param>
    /// <returns></returns>
    public static bool SetCookie(string strName, string strValue, int strMinutes)
    {
        try
        {
            if (System.Web.HttpContext.Current.Request.Cookies[strName] != null)
            {
                System.Web.HttpContext.Current.Response.Cookies[strName].Expires = DateTime.Now.AddDays(-1);
            }
            HttpCookie cookie = new HttpCookie(strName);
            //cookie.domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
            cookie.Expires = DateTime.Now.AddMinutes(strMinutes);
            cookie.Value = HttpUtility.UrlEncode(strValue);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }
    /// <summary>
    /// 读取cookies
    /// </summary>
    /// <param name="strname">主键</param>
    /// <returns></returns>
    public static string GetCookie(string strname)
    {
        HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[strname];
        if (cookie != null)
        {
            if (!string.IsNullOrEmpty(cookie.Value))
                return HttpUtility.UrlDecode(cookie.Value.ToString());
            else
                return null;
        }
        else
        {
            return null;
        }
    }
    /// <summary>
    /// 删除cookies
    /// </summary>
    /// <param name="strname">主键</param>
    /// <returns></returns>
    public static bool DelCookie(string strname)
    {
        try
        {
            HttpCookie cookie = new HttpCookie(strname);
            //cookie.domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
            cookie.Expires = DateTime.Now.AddDays(-1);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }
    #endregion

}
